package com.hd.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hd.common.core.domain.R;
import com.hd.common.core.enums.ResultCode;
import com.hd.common.core.enums.UserIdentity;
import com.hd.common.security.exception.ServiceException;
import com.hd.common.security.service.TokenService;
import com.hd.system.domain.SysUser;
import com.hd.system.domain.dto.SysUserSaveDTO;
import com.hd.system.mapper.SysUserMapper;
import com.hd.system.service.ISysUserService;
import com.hd.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RefreshScope
//@RefreshScope是用来要进行secret要进行变更时也不要重启服务就可以把secret的值进行变更
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;
    @Override
    public R<String> login(String userAccount, String password) {
        //通过数据库的数据进行账号，密码的验证，然后进行是否成功登录
        //mybatis-plus可以newLamb表达式进行调用
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getUserId,SysUser::getPassword).eq(SysUser::getUserAccount,userAccount));

        //int a = 100/0;
        //用户有三种结果
        //1.用户不存在
        R loginResult = new R();
        if(sysUser == null){
//            loginResult.setCode(ResultCode.FAILED_USER_NOT_EXISTS.getCode());
//            loginResult.setMsg(ResultCode.FAILED_USER_NOT_EXISTS.getMsg());
//            return loginResult;
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //2.登录成功
        if(BCryptUtils.matchesPassword(password,sysUser.getPassword())){
//            loginResult.setCode(ResultCode.SUCCESS.getCode());
//            loginResult.setMsg(ResultCode.SUCCESS.getMsg());
//            return loginResult;
            //return R.ok(token);

            // 过期时间我们要如何进行存储  过期时间应该设计多久  720分钟
            return R.ok( tokenService.createtoken(sysUser.getUserId(),secret, UserIdentity.ADMIN.getValue()));
        }
        //3.账号或者密码错误
//        loginResult.setCode(ResultCode.FAILED.getCode());
//        loginResult.setMsg(ResultCode.FAILED.getMsg());
//        return loginResult;
        return R.fail(ResultCode.FAILED_LOGIN);

    }
    @Override
    public int add(SysUserSaveDTO sysUserSaveDTO) {
        // 将DTO转化为实体
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());

        // 检查用户是否存在
        List<SysUser> sysUserList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));
        if (!CollectionUtil.isEmpty(sysUserList)) {
            // 用户已存在，抛出异常
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }

        // 设置其他字段
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
        sysUser.setCreateBy("zhangsan"); // 假设"zhangsan"是创建用户的标识
        sysUser.setCreateTime(LocalDateTime.now()); // 设置创建时间
        sysUser.setUpdateTime(LocalDateTime.now()); // 设置最后更新时间

        // 执行插入操作
        return sysUserMapper.insert(sysUser);


    }

}
